<template>
  <div class="page-container">
    <!--工具栏-->
    <div class="toolbar" style="float:left;padding-top:10px;">
      <el-form :inline="true" :model="filters" :size="size">
        <el-form-item>
          <el-input v-model="filters.keyword" placeholder="用户名" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" icon="el-icon-search" @click="findPage">{{$t('action.search')}}</el-button>
          <!-- <kt-button icon="fa fa-search" :label="$t('action.search')" perms="sys:user:select" type="primary" @click="findPage(null)"/> -->
        </el-form-item>
        <el-form-item>
          <kt-button icon="fa fa-plus" :label="$t('action.add')" perms="sys:user:save" type="primary" @click="handleAdd" />
        </el-form-item>
      </el-form>
    </div>

    <cs-table :table-data="tableData"
              :table-label="tableLabel"
              @handleButton="handleButton"
              :loading="loading"
              :isSelection="isSelection"
              @handleSortChange="handleSortChange"
              @handleSelectionChange="handleSelectionChange"
              :table-option="tableOption">
      <template slot="status" slot-scope="scope">
        <el-switch
          v-model="scope.row.status === '0' ? true : false"
          @change="handleSwitch(scope.row)"
        >
        </el-switch>
      </template>
    </cs-table>

    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageRequest.pageNo"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageRequest.pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
      style="text-align: right;"
      >
    </el-pagination>

    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogVisible"
      :append-to-body="true"
      :close-on-click-modal="false"
      @close="handleColse"
      width="40%"
			>
      <el-form
        :model="dataFormRules"
        :rules="dataFormRules"
        ref="dataForm"
        size="small"
        v-if="userRole"
        label-width="80px">
        <el-form-item
          label="角色授权"
          prop="roleIds">
          <el-select
            v-model="dataFormRules.roleIds"
            multiple
            placeholder="请选择"
            style="width: 100%;"
            value="">
            <el-option
              v-for="item in group"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId"/>
          </el-select>
        </el-form-item>
      </el-form>
      <el-form
        :model="dataForm"
        :rules="rules"
        ref="dataForm"
        size="small"
        v-else
        label-width="80px">
        <el-form-item
          label="账号"
          prop="account">
          <el-input
            v-model="dataForm.account"
            :disabled="dialogStatus !== 'create'"
            placeholder="请输入账号"
            :clearable="true"/>
        </el-form-item>

        <el-form-item
          v-if="dialogStatus === 'create'"
          label="密码"
          prop="password">
          <el-input
            type="password"
            v-model="dataForm.password"
            placeholder="请输入密码"
            :clearable="true"/>
        </el-form-item>

        <el-form-item
          v-if="dialogStatus === 'create'"
          label="确认密码"
          prop="password_confirm">
          <el-input
            type="password"
            v-model="dataForm.password_confirm"
            placeholder="请再次输入密码"
            :clearable="true"/>
        </el-form-item>

        <el-form-item
          label="昵称"
          prop="name">
          <el-input
            v-model="dataForm.name"
            placeholder="请输入昵称"
            :clearable="true"/>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item
              label="性别"
              prop="sex">
              <el-select
                v-model="dataForm.sex"
                placeholder="请选择"
                value="">
                <el-option
                  v-for="item in sexOption"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="11">
            <el-form-item
              label="生日"
              prop="birthday">
              <el-date-picker
                v-model="dataForm.birthday"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
                style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item
          label="手机号"
          prop="phone">
          <el-input
            v-model="dataForm.phone"
            placeholder="请输入手机号"
            :clearable="true"/>
        </el-form-item>

        <el-form-item
          label="邮箱"
          prop="email">
          <el-input
            type="email"
            v-model="dataForm.email"
            placeholder="请输入邮箱"
            :clearable="true"/>
        </el-form-item>

				<el-form-item
          label="所属部门"
          prop="deptId">
          <treeselect
            v-model="dataForm.deptId"
            :clearable="true"
            placeholder="请选择上级部门"
            noChildrenText="不好意思哟~,没有下一级了~~"
            :normalizer="normalizer"
            :options="deptData"/>
        </el-form-item>

<!--        <el-form-item-->
<!--          label="状态"-->
<!--          prop="status">-->
<!--          <el-switch-->
<!--            v-model="dataForm.status"-->
<!--            active-value="0"-->
<!--            inactive-value="1">-->
<!--          </el-switch>-->
<!--        </el-form-item>-->
      </el-form>

      <div slot="footer" class="dialog-footer" v-if="!userRole">
        <el-button
          @click="dialogVisible = false"
          size="small">取消</el-button>

        <el-button
          v-if="dialogStatus === 'create'"
          type="primary"
          :loading="dialogLoading"
          @click="submitForm"
          size="small">确定</el-button>
        <el-button
          v-else type="primary"
          :loading="dialogLoading"
          @click="submitForm"
          size="small">修改</el-button>
      </div>
      <div slot="footer" class="dialog-footer" v-if="userRole">
        <el-button
          @click="dialogVisible = false"
          size="small">取消</el-button>

        <el-button
          type="primary"
          :loading="dialogLoading"
          @click="handleSubmitForm"
          size="small">确定</el-button>
      </div>
    </el-dialog>

    <!-- 密码重置后弹出框 -->
    <el-dialog
      title="提示"
      :visible.sync="dialogResetPsd"
      width="30%"
    >
      <span>重置后密码为: {{ resetedPsd }}</span>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogResetPsd = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import PopupTreeInput from "@/components/PopupTreeInput"
import KtButton from "@/views/Core/KtButton"
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog"
import { format } from "@/utils/datetime"
import { getAdminListPage, getAdminItem, delAdminList, addAdminItem, getTreeDept, resetAdminItem, addUserRole, queryUserRoles, updateUsersStatus } from '@/api/auth/user'
import { getAuthGroupList } from '@/api/auth/group'
import { message } from '@/utils/message'
import { hasPermission } from '@/permission/index.js'
import { validatePassword } from '@/utils/validateRules'
export default {
	components:{
		PopupTreeInput,
		'CsTable': () => import('@/components/cs-table'),
		KtButton,
		TableColumnFilterDialog,
    Treeselect
	},
	data() {
		let validateConfirmPassword = (rule, value, callback) => {
      if (this.dataForm.password !== value) {
        callback(new Error('确认密码与新密码不一致'))
      } else {
        callback()
      }
    }
		return {
      isSelection: false,
			size: window.SITE_CONFIG.tableSize,
			filters: {
				keyword: ''
			},
      dataFormRules: {
        roleIds: [],
        userId: ''
      },
      loading: true,
			tableLabel: [
        { label: '账号', param: 'account', align: 'center', sortable: false, isShow: true },
        { label: '昵称', param: 'name', align: 'center', isShow: true },
        // { label: '角色', param: 'roleNames', align: 'center', sortable: false, isShow: true },
        { label: '性别',
          param: 'sex',
          align: 'center',
          sortable: false,
          render: (row) => {
            if (row.sex === '1') {
              return '男'
            } else if (row.sex === '2') {
              return '女'
            } else {
              return '未知'
            }
          }
        },
        { label: '邮箱', param: 'email', align: 'center', sortable: false, isShow: true },
        { label: '电话', param: 'phone', align: 'center', sortable: false, isShow: true },
        { label: '状态', param: 'status', align: 'center', sortable: false, slot: true, isShow: true },
        { label: '创建时间',
          param: 'createTime',
          align: 'center',
          sortable: false,
          render: (row) => {
            return format(row.createTime)
          }
        }
      ],
      tableOption: {
        label: '操作',
        width: '380',
        options: [
          { label: '编辑', type: '', icon: 'el-icon-edit', methods: 'audit', auth: 'sys:user:update' },
          { label: '授权', type: 'primary', icon: 'el-icon-document-checked', methods: 'userRole', auth: 'sys:userRole:save' },
          { label: '重置密码', type: 'warning', icon: 'el-icon-refresh-right', methods: 'reset', auth: 'sys:user:reset' },
          { label: '删除', type: 'danger', icon: 'el-icon-delete', methods: 'delete', auth: 'sys:user:delete' }
        ]
			},
      tableData: [],
      totalPage: 0,
			multipleSelection: [],
			pageRequest: { pageNo: 1, pageSize: 10 },
			dialogVisible: false, // 新增编辑界面是否显示
			dataFormRules: {
				name: [
					{ required: true, message: '请输入用户名', trigger: 'blur' }
				]
			},
			dialogLoading: false,
      dialogStatus: '',
      textMap: {
        update: '编辑用户',
        create: '新增用户',
        createRole: '配置角色'
      },
      sexOption: [
        { name: '男', value: '1' },
        { name: '女', value: '2' }
			],
			// 新增编辑界面数据
			dataForm: {
				userId: '',
        account: '',
        name: '',
        password: '',
				password_confirm: '',
				deptId: '',
        birthday: null,
        email: '',
        phone: '',
        sex: '',
        status: '0'
			},
      userRole: '',
			deptData: [],
      normalizer(node) {
        return {
          label: node.fullName
        }
      },
			// deptName: '',
			// deptTreeProps: {
			// 	label: 'fullName',
			// 	children: 'children'
			// },
			group: [],
      dataFormRules: {
        roleIds: [
          {
            required: true,
            message: '至少选择一项',
            trigger: 'change'
          }
        ]
      },
			rules: {
        account: [
          {
            required: true,
            message: '账号不能为空',
            trigger: 'blur'
          },
          {
            min: 4,
            max: 20,
            message: '长度在 4 到 20 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '密码不能为空',
            trigger: 'blur'
          },
          {
            validator: validatePassword, trigger: 'change'
          },
          {
            min: 6,
            max: 20,
            message: '请输入密码长度6至20位',
            trigger: 'blur'
          }
        ],
        password_confirm: [
          {
            required: true,
            message: '确认密码不能为空',
            trigger: 'blur'
          },
          { validator: validateConfirmPassword, trigger: 'change' }
        ],
        name: [
          {
            required: true,
            message: '昵称不能为空',
            trigger: 'blur'
          },
          {
            max: 50,
            message: '长度不能大于 50 个字符',
            trigger: 'blur'
          }
        ]
				// deptId: [
        //   {
        //     required: true,
        //     message: '至少选择一项',
        //     trigger: 'change'
        //   }
        // ]
      },
      dialogResetPsd: false,
      resetedPsd: ''
    }
	},
	mounted() {
    // this.findDeptTree()
    this.findPage()
	},
	methods: {
    hasPerms: function (perms) {
      // 根据权限标识和外部指示状态进行权限判断
      // return true
      return hasPermission(perms) & !this.disabled
    },
    handleSwitch (val) {
      const parms = {
        id: val.userId
      }
      this.$confirm(`确认${val.status === '0' ? '禁用' : '启用'}该数据？`, '提示', {})
        .then(() =>
          updateUsersStatus(parms).then(res => {
          if (res.code === 200) {
            this.findPage()
          }
        }))
    },
	  // 角色授权
    handleSubmitForm () {
      this.dataFormRules.roleIds = this.dataFormRules.roleIds.join(',')
      if (!this.dataFormRules.roleIds) {
        message({
          message: '至少选择一项',
          type: 'error'
        })
        return
      }
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          this.dialogLoading = true
          let params = {
            userId: this.dataFormRules.userId,
            roleIds: this.dataFormRules.roleIds
          }
          addUserRole(params).then((res) => {
            this.dialogLoading = false
            if(res.code == 200) {
              this.dialogVisible = false
              this.$refs['dataForm'].resetFields()
            }
            this.findPage()
          })
        }
      })
    },
		handleButton(methods, row, index) {
      this.userRole = ''
      // 修改
      if (methods.methods === 'audit') {
        this.handleUpdate(methods.row)
      } else if (methods.methods === 'delete') { // 删除
        this.handleDelete(methods.row)
      } else if (methods.methods === 'reset') { // 重置密码
        this.resetPassword(methods.row)
      } else if (methods.methods === 'userRole') {
        this.userRole = 'userRole'
        this.handleUpdate(methods.row, true)
      }
    },
    // 排序
    handleSortChange(val) {
      console.log(val)
		},
		// 选中数据项
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 每页数
		sizeChangeHandle (val) {
			this.pageRequest.pageSize = val
			this.pageRequest.pageNo = 1
			this.findPage()
		},
		// 当前页
		currentChangeHandle (val) {
			this.pageRequest.pageNo = val
			this.findPage()
    },
		// 获取分页数据
		findPage() {
		  this.loading = true
			this.pageRequest.keyword = this.filters.keyword
			getAdminListPage(this.pageRequest).then((res) => {
        this.tableData = res.data.rows
        this.totalPage = res.data.totalRows
        this.loading = false
			})
		},
		// 加载用户角色信息
		findUserRoles: function () {
			getAuthGroupList().then((res) => {
				// 加载角色集合
        this.group = res.data
			})
		},
		// 批量删除
		handleDelete(data) {
			this.$confirm('确认删除这条数据吗？', '提示', {})
			.then(() => {
				delAdminList(data.userId)
				.then(res => {
					this.findPage()
				})
			})
		},
		// 显示新增界面
		handleAdd: function () {
		  this.userRole = ''
      this.findUserRoles()
		  this.findDeptTree()
			this.dialogVisible = true
			this.dialogStatus = 'create'
			this.dataForm = {
				id: 0,
				name: '',
				password: '',
				deptId: null,
				deptName: '',
				email: '',
				mobile: '13889700023',
				status: 1,
				userRoles: []
			}
		},
		// 显示编辑界面
		handleUpdate(params, flag) {
      // console.log(params)
      this.dataFormRules.userId = params.userId
      this.findUserRoles()
      if (!flag) {
        this.findDeptTree()
      }
			this.dialogStatus = 'update'
      if (this.userRole) {
        this.dialogVisible = true
        this.dataFormRules.roleIds = []
        this.dialogStatus = 'createRole'
        queryUserRoles(params.userId).then(res => {
          if (res.data.length > 0) {
            this.dataFormRules.roleIds = res.data.map(item => {
              return item.roleId
            })
          } else {
            this.dataFormRules.roleIds = []
          }
        })
      } else {
        getAdminItem(params.userId).then(res => {
          if (res) {
            this.dialogVisible = true
            res.data.birthday = res.data.birthday ? new Date(res.data.birthday) : null
            this.dataForm = res.data
          }
        })
      }

			// let userRoles = []
			// for(let i=0,len=params.row.userRoles.length; i<len; i++) {
			// 	userRoles.push(params.row.userRoles[i].roleId)
			// }
			// this.datadataForm.userRoles = userRoles
    },
    // 重置密码
    resetPassword(row) {
      let params = {
        userId: row.userId
      }
      this.$confirm('确认重置密码吗？', '提示', {}).then(() => {
        resetAdminItem(params).then(res => {
          if (res.code === 200) {
            this.dialogResetPsd = true
            this.resetedPsd = res.data
          }
        })
      })
    },
		// 编辑
		submitForm: function () {
			this.$refs.dataForm.validate((valid) => {
				if (valid) {
					this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.dialogLoading = true
            this.dataForm.id = this.dataForm.userId
						let params = Object.assign({}, this.dataForm)
						addAdminItem(params).then((res) => {
							this.dialogLoading = false
							if(res.code == 200) {
								this.dialogVisible = false
								this.$refs['dataForm'].resetFields()
							}
							this.findPage()
						})
					})
				}
			})
		},
		// 获取部门列表
		findDeptTree: function () {
			getTreeDept().then((res) => {
        if (res) {
          this.deptData = res.data
        }
			})
		},
		// 菜单树选中
		deptTreeCurrentChangeHandle (data, node) {
			this.datadataForm.deptId = data.id
			this.datadataForm.deptName = data.name
		},
		// 时间格式化
		dateFormat: function (row, column, cellValue, index){
    	return format(row[column.property])
    },
		// 处理表格列过滤显示
	  displayFilterColumnsDialog: function () {
			this.$refs.tableColumnFilterDialog.setDialogVisible(true)
	  },
		// 处理表格列过滤显示
	  handleFilterColumns: function (data) {
			this.filterColumns = data.filterColumns
			this.$refs.tableColumnFilterDialog.setDialogVisible(false)
	  },
		// 部门树选中
    handleTreeSelectChange(data, node) {
      this.dataForm.deptId = data.id;
      this.deptName = data.fullName;
    },
    // 关闭对话框，重置表单
    handleColse() {
      this.$refs.dataForm.resetFields()
    }
	}
}
</script>

<style scoped>
.page-container{
  height: 100%;
}
</style>
